package cn.hfatec.shms.web.members.customer.service;

import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.base.BaseDao;
import cn.hfatec.shms.advice.annotation.MysqlDataSource;
import cn.hfatec.shms.advice.annotation.MysqlDataSourceXm;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.constants.ShmsProperties;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.exception.NotAuthException;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.utils.ExcelUtil;
import cn.hfatec.shms.web.members.customer.dao.CustomerDao;
import cn.hfatec.shms.web.members.customer.model.Customer;
import cn.hfatec.shms.web.members.customer.model.CustomerCheck;
import cn.hfatec.shms.web.members.customer.model.CustomerParams;
import com.google.common.base.Optional;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;


/**
 * @author hfatec
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Service("CustomerService")
public class CustomerService {

    public static final String BEAN_ID = "CustomerService";

    //注入Dao层
    @Resource(name = "CustomerDao")
    private CustomerDao customerDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;

    @Resource(name = "shmsProperties")
    private ShmsProperties shmsProperties;

    @Transactional
    @MysqlDataSource
    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     * 查询数据
     *
     * @param customerParams
     * @param page
     */
    @Transactional
    @MysqlDataSourceXm
    public Table queryCustomerTable(CustomerParams customerParams, Page page) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", customerParams);
        return baseDao.queryTableByPage("queryCustomer", params, page);
    }

    /**
     * 插入数据
     *
     * @param customer
     */
    @Transactional
    @MysqlDataSource
    public void saveCustomer(Customer customer, User user) {
        if (customer.getId() != null) {
            Customer result = getCustomer(customer.getId());
            if (result != null) {
                customerDao.update(customer);
            } else {
                customer.setCreateTime(new Date());
                customer.setCreateUser(user.getLoginName());
                customerDao.insert(customer);
            }
        } else {
            customer.setCreateUser(user.getLoginName());
            customer.setCreateTime(new Date());
            customerDao.insert(customer);
        }
    }

    /**
     * 删除数据
     *
     * @param id
     */
    @Transactional
    @MysqlDataSource
    public void deleteCustomer(Integer id) {

        customerDao.delete(id);
    }

    /**
     * 删除数据
     *
     * @param customerList
     */
    @Transactional
    @MysqlDataSource
    public void deleteCustomerBatch(List<String> customerList) {
        for (String id : customerList) {
            deleteCustomer(Integer.valueOf(id));
        }
    }

    /**
     * 根据ID获取数据
     *
     * @param id
     */
    @Transactional
    @MysqlDataSource
    public Customer getCustomer(Integer id) {

        return customerDao.getCustomerById(id);
    }

    /**
     * 导入潜在客户
     *
     * @param path
     * @param request
     * @param response
     * @return
     * @throws java.io.IOException
     */
    @Transactional
    @MysqlDataSource
    public String importCust(String path, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String filePath = path.substring(path.indexOf("/upload") + 7);
        User user = (User) request.getSession().getAttribute(ShmsConstant.LOGIN_USER_SESSION_NAME);
        if (user == null) {
            throw new NotAuthException("用户未授权");
        }
        String uploadPath = shmsProperties.getUploadPath();
        File file = new File(uploadPath + File.separator + filePath);
        boolean flag = false;
        String rule = "^1[358]\\d{9}$";
        String errorMsg = "";
        Workbook workbook = null;
        workbook = WorkbookFactory.create(file);
        Sheet sh = workbook.getSheetAt(0);//
        List<CustomerCheck> potentialCusts = this.buildCustWithAjaxUpload(sh);//
        if (potentialCusts != null && potentialCusts.size() > 0) {
            for (CustomerCheck customCheck : potentialCusts) {
                //判读是否为有效数据
                if (customCheck.isValid()) {
                    Customer custom = customCheck.getCustom();
                    Optional<JsonResponse<String>> optional = checkCustByUniqueConstraint(custom);
                  if (!custom.getPhone().matches(rule)) {
                        errorMsg += "第" + customCheck.getRowNumber() + "数据，客户姓名=【" + custom.getPhone() + "】,手机=【" + custom.getPhone() + "】的手机号不符合格式（13,15,18开头的11位号码）,不能导入!";
                        continue;
                    }
                    if (optional.isPresent()) {
                        errorMsg += "第" + customCheck.getRowNumber() + "数据，卡号=【" + custom.getCardId() + "】已经存在,不能导入!";
                        continue;
                    }
//                    custom.setCustomSource(ShmsConstant.CUSTOM_SOURCE_PL);//默认为人工采集);
                    saveCustomer(custom, user);
                    flag = true;
                } else {//无效数据
                    errorMsg += "第" + customCheck.getRowNumber() + "行的客户姓名或卡号为空，不能导入!";
                }
            }
        } else {
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "导入的文件无符合数据").toString();
        }

        if (flag) {
            if ("".equals(errorMsg)) {
                return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "导入成功!" + errorMsg).toString();
            }
            return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "部分导入成功!" + errorMsg).toString();
        } else {
            return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "导入失败!" + errorMsg).toString();
        }

    }

    /**
     * 读取潜在客户导入的数据
     *
     * @param sh
     * @return
     * @throws Exception
     */
    @Transactional
    @MysqlDataSource
    private List<CustomerCheck> buildCustWithAjaxUpload(Sheet sh) throws Exception {
        List<CustomerCheck> checks = new ArrayList<CustomerCheck>();
        int rows = sh.getLastRowNum() + 1 - sh.getFirstRowNum(); // 总行数
        List<CodeInfo> sexList = CodeInfoCache.getCodeInfo(CodeType.SEX);
//        List<CodeInfo> nationList = CodeInfoCache.getCodeInfo(CodeType.NATION);
//        List<CodeInfo> certTypeList = CodeInfoCache.getCodeInfo(CodeType.CERT_TYPE);
//        List<CodeInfo> educationList = CodeInfoCache.getCodeInfo(CodeType.EDUCATION);

        ExcelUtil excelUtil = new ExcelUtil();

        for (int i = 0; i < rows; i++) {
            boolean flag = true;//数据是否有效(客户姓名，手机号存在)
            boolean flag2 = false;//判断是否该行有数据
            Customer cust = new Customer();
            CustomerCheck customCheck = new CustomerCheck();
            customCheck.setRowNumber(i);
            customCheck.setValid(true);
            String str = "";//下拉框
            // HSSFRow row = sh.getRow(i);//excel97-2003写法
            Row row = sh.getRow(i);
//            int cols = row.getLastCellNum() + 1 - row.getFirstCellNum(); // 该行的总列数
            Iterator cells = row.cellIterator();
            int j = 0;
            while (cells.hasNext()) {
                //判断行数据的客户姓名和电话是否为空，某一项为空则不执行循环
                if (StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, 0)) || StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, 1))) {
                    for (int r = 0; r <= 10; r++) {
                        if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, r))) {
                            if (!flag2) {
                                customCheck.setValid(false);
                                flag2 = true;
                            }
                        }
                    }
                    flag = false;
                    break;
                }

//                HSSFCell cell = (HSSFCell) cells.next();//excel97-2003写法
                XSSFCell cell = (XSSFCell) cells.next();

                if (j == 0) {
                    //卡号
                    if (StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        throw new Exception("第【" + i + "】行数据，客户卡号不能为空！");
                    }
                    cust.setCardId(ExcelUtil.getStringRowCellValue(row, j));
                } else if (j == 1) {
                    // 客户姓名
                    if (StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        throw new Exception("第【" + i + "】行数据，客户姓名不能为空！");
                    }
                    cust.setCustomerName(excelUtil.getStringRowCellValue(row, j));
                } else if (j == 2) {
                    // 年龄
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        cust.setAge(Integer.valueOf(ExcelUtil.getStringRowCellValue(row, j)));
                    }
                } else if (j == 3) {

                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        cust.setSex(Integer.valueOf(ExcelUtil.getStringRowCellValue(row, j)));
                    }
                  /*  // 性别
                    str = excelUtil.getStringRowCellValue(row, j);
                    if (!StringUtils.isEmpty(str)) {
                        for (CodeInfo c : sexList) {
                            if (c.getContent().equals(str)) {
                                cust.setSex(Integer.parseInt(c.getValue()));
                            }
                        }
                    }*/
                } else if (j == 4) {
                    // 电话
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        cust.setPhone(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 5) {
                    // 身份证
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        cust.setStaffId(excelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 6) {
                    // 地址
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        cust.setAddress(excelUtil.getStringRowCellValue(row, j));
                    }
                }
                j++;
            }
            if (flag) {
//                 list.add(cust);
                customCheck.setCustom(cust);
                checks.add(customCheck);
            } else {
//                customCheck.setCustom(cust);
                if (flag2) {
                    checks.add(customCheck);
                }
            }
        }
        return checks;
    }

    /**
     * 根据客户姓名和手机查询唯一性
     *
     * @param cust
     * @return
     */
    @Transactional
    @MysqlDataSource
    public Optional checkCustByUniqueConstraint(Customer cust) {
        Customer custom = customerDao.getCustomerByCardId(cust.getCardId());
        if (cust.getId() == null) {
            if (custom != null) {
                return Optional.of(new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "卡号=【" + cust.getCardId() + "】已经存在,不能新增!"));
            }
        } else {
            if (custom != null) {
                if (!custom.getId().equals(cust.getId())) {
                    return Optional.of(new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "卡号=【" + cust.getCardId() + "】已经存在,不能编辑!"));
                }
            }
        }
        return Optional.absent();
    }

    /**
     * 导出
     *
     * @param
     */
    @Transactional
    @MysqlDataSource
    public String exportExcel(CustomerParams customerParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            String clientFileName = encodeFilename(request, System.currentTimeMillis() + "");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName + ".xls");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            List dataList = customerDao.queryCustomer(customerParams);
            List nameList = new ArrayList();
            nameList.add("卡号");
            nameList.add("姓名");
            nameList.add("年龄");
            nameList.add("性别");
            nameList.add("身份证");
            nameList.add("地址");
            this.exportExcel(nameList, dataList, os);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @return HSSFWorkbook
     */
    public HSSFWorkbook createWorkbook(List fieldName, List fieldData) {
        List<CodeInfo> sexTypeList = CodeInfoCache.getCodeInfo(CodeType.SEX);

        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("体适能报表");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCellStyle cellstyle = (HSSFCellStyle) wb.createCellStyle();// 设置表头样式
        cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
        cellstyle.setWrapText(true); // 设置为自动换行
        HSSFFont cellFont = (HSSFFont) wb.createFont(); // 创建表头字体样式
        cellFont.setFontHeightInPoints((short) 10); // 设置字体大小
        cellFont.setFontName("宋体"); // 设置字体类型
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        cellstyle.setFont(cellFont); // 为表头样式设置字体样式


        for (int i = 0; i < fieldName.size(); i++) {
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue((String) fieldName.get(i));
            cell.setCellStyle(cellstyle);
        }

        Customer customer = null;

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        for (int i = 0; i < fieldData.size(); i++) {
            row = sheet.createRow(i + 1);
            customer = (Customer) fieldData.get(i);
            // 第四步，创建单元格，并设置值
            row.createCell((short) 0).setCellValue(customer.getCustomerName());
            if (customer.getCardId() == null) {
                row.createCell((short) 1).setCellValue("");
            } else {
                row.createCell((short) 1).setCellValue(customer.getCardId());
            }
            if (customer.getAge() == null) {
                row.createCell((short) 2).setCellValue("");
            } else {
                row.createCell((short) 2).setCellValue(customer.getAge());
            }
            if (customer.getSex() == null) {
                row.createCell((short) 3).setCellValue("");
            } else {
                for (CodeInfo c : sexTypeList) {//汉化性别信息
                    if (c.getValue().equals(customer.getSex() + "")) {
                        row.createCell((short) 3).setCellValue(c.getContent());
                        break;
                    }
                }
            }

            if (customer.getStaffId() == null) {
                row.createCell((short) 4).setCellValue("");
            } else {
                row.createCell((short) 4).setCellValue(customer.getStaffId());
            }
            if (customer.getAddress() == null) {
                row.createCell((short) 5).setCellValue("");
            } else {
                row.createCell((short) 5).setCellValue(customer.getAddress());
            }
        }
        //自适应列宽
        for (int i = 0; i < fieldName.size(); i++) {
            sheet.autoSizeColumn((short) i);
        }


        return wb;
    }


    //将信息写入输出流的方法。
    public void exportExcel(List fieldName, List fieldData, OutputStream os) throws Exception {
        HSSFWorkbook wb = createWorkbook(fieldName, fieldData);
        wb.write(os);
        os.close();
    }


}